chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'downloadVideo') {
    const videoId = new URL(request.videoUrl).searchParams.get('v');
    if (!videoId) {
      console.error('无效的 YouTube URL');
      return;
    }

    // 连接到本地 Native Host
    const port = chrome.runtime.connectNative('com.youtube.downloader');
    
    port.onMessage.addListener((response) => {
      if (response.status === 'success') {
        chrome.downloads.download({
          url: response.downloadUrl,
          filename: `youtube-${videoId}.mp4`
        });
      } else {
        console.error('下载失败:', response.error);
      }
    });

    port.postMessage({
      action: 'download',
      videoId: videoId,
      quality: '1080p'  // 可以根据需要调整视频质量
    });

    port.onDisconnect.addListener(() => {
      if (chrome.runtime.lastError) {
        console.error('Native Host 连接错误:', chrome.runtime.lastError);
      }
    });
  }
});